<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\common\controller\Common;
use app\user\model\User as UserModel;
use app\user\model\Role as RoleModel;
use app\admin\model\Menu as MenuModel;
use think\facade\Hook;
use think\facade\Request;
/**
 * 用户公开控制器，不经过权限认证
 * @package app\user\admin
 */
class Publics extends Common
{
    /**
     * 用户登录
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function signin()
    {
        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            $rememberme = isset($data['remember-me']) ? true : false;

            // 登录钩子
            $hook_result = Hook::listen('signin', $data);
            if (!empty($hook_result) && true !== $hook_result[0]) {
                $this->error($hook_result[0]);
            }

            // 验证数据
            $result = $this->validate($data, 'User.signin');
            if(true !== $result){
                // 验证失败 输出错误信息
                $this->error($result);
            }

            // 验证码
            if (config('captcha_signin')) {
                $captcha = $this->request->post('captcha', '');
                $captcha == '' && $this->error('请输入验证码');
                if(!captcha_check($captcha, '')){
                    //验证失败
                    $this->error('验证码错误或失效');
                }
            }

            // 登录
            $UserModel = new UserModel;
            $uid = $UserModel->login($data['username'], $data['password'], $rememberme);
            if ($uid) {
                // 记录行为
                action_log('user_signin', 'admin_user', $uid, $uid);
                $this->jumpUrl();
            } else {
                $this->error($UserModel->getError());
            }
        } else {

            $hook_result = Hook::listen('signin_sso');
            if (!empty($hook_result) && true !== $hook_result[0]) {
                if (isset($hook_result[0]['url'])) {
                    $this->redirect($hook_result[0]['url']);
                }
                if (isset($hook_result[0]['error'])) {
                    $this->error($hook_result[0]['error']);
                }
            }

            if (is_signin()) {
                $this->jumpUrl();
            } else {
                return $this->fetch();
            }
        }
    }

    /**
     * 跳转到第一个有权限访问的url
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed|string
     */
    private function jumpUrl()
    {
        if (session('user_auth.role') == 1) {
            $this->success('Login succeeded', url('admin/index/profile'));
        }

        $default_module = RoleModel::where('id', session('user_auth.role'))->value('default_module');
        $menu = MenuModel::get($default_module);
        if (!$menu) {
            $this->error('The current role does not specify a default jump module！');
        }

        if ($menu['url_type'] == 'link') {
            $this->success('Login succeeded', $menu['url_value']);
        }

        $menu_url = explode('/', $menu['url_value']);
        role_auth();

        $menus = MenuModel::getSidebarMenu($default_module, $menu['module'], $menu_url[1]);
        $url   = '';
        foreach ($menus as $key => $menu) {
            if (!empty($menu['url_value'])) {
                $url = $menu['url_value'];
                break;
            }
            if (!empty($menu['child'])) {
                $url = $menu['child'][0]['url_value'];
                break;
            }
        }

        if ($url == '') {
            $this->error('Insufficient permissions');
        } else {
            $this->success('Login succeeded', $url);
        }
    }

    /**
     * 退出登录
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function signout()
    {
        $hook_result = Hook::listen('signout_sso');
        if (!empty($hook_result) && true !== $hook_result[0]) {
            if (isset($hook_result[0]['url'])) {
                $this->redirect($hook_result[0]['url']);
            }
            if (isset($hook_result[0]['error'])) {
                $this->error($hook_result[0]['error']);
            }
        }

        session(null);
        cookie('uid', null);
        cookie('signin_token', null);

        $this->redirect('signin');
    }

    public function forget(){
        if ($this->request->isPost()) {
            $email=$this->request->param('email','');
            if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $email)) {
                $username=UserModel::where(['email' => $email])->value('username');
                if (!$username) {
                    $this->error('Email does not exist');
                }
                //发送邮件
                $token=token(40);
                $reset_url=Request::domain().url('reset').'?token='.$token;
                UserModel::where(['email' => $email])->update(['token'=>$token]);
                $ip=get_client_ip();
                $html=<<<EOF
A new password was requested for envee administration.

To reset your password click on the link below:

$reset_url

The IP used to make this request was:

$ip
EOF;
                if(send_email($username,'Password reset request',$html,$email)){
                    $this->success('Email send success');
                }else{
                    $this->error('Email send failed');
                }
            }else{
                $this->error('Incorrect Email');
            }
        }else{
            if (is_signin()) {
                $this->jumpUrl();
            } else {
                return $this->fetch();
            }
        }
    }

    public function reset(){
        if ($this->request->isPost()) {
            $password=$this->request->param('password');
            $rePassword=$this->request->param('confirm');
            $token=$this->request->param('token');
            if($password!=$rePassword) $this->error('Password and password confirmation do not match!');
            $id=UserModel::where(['token' => $token])->value('id');
            if(!$id) $this->error('token invalid!');
            $data['id']=$id;
            $data['password']=$password;
            if (UserModel::update($data)) {
                UserModel::update(['id'=>$id,'token'=>'']);
                $this->success('modify password success',url('signin'));
            }else{
                $this->error('modify password failed');
            }

        }else{
            if (is_signin()) {
                $this->jumpUrl();
            } else {
                $token=$this->request->get('token');
                $this->assign('token',$token);
                return $this->fetch();
            }
        }
    }
}
